from django import forms
from web.forms.bootstarp import BootStrapForm
from web import models
from django.core import validators
from .widgets import ColorRadioSelect


class ProjectModelForm(BootStrapForm, forms.ModelForm):
    bootstrap_class_exclude = ['color']

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'desc': forms.Textarea,
            'color': ColorRadioSelect(attrs={'class': 'color-radio'}),
        }

    def clean_name(self):
        # 判断当前用户是否创建
        name = self.cleaned_data.get('name')
        exists = models.Project.objects.filter(name=name, creator=self.request.tracer.user).exists()
        if exists:
            raise validators.ValidationError('项目名已存在')
        # 判断已创建多少项目
        count = models.Project.objects.filter(creator=self.request.tracer.user).count()

        if count >= self.request.tracer.price_policy.project_num:
            raise validators.ValidationError('项目个数超限,请购买套餐')

        return name
